﻿// 20. Write a program that reads two numbers N and K and generates all the variations of K elements from the set [1..N]. Example:
// N = 3, K = 2 -> {1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}

using System;

class VariationsOfKElements
{
    static void Main()
    {
        // get number N
        Console.Write("Enter number N : ");
        string numberNStr = Console.ReadLine();
        int numberN;
        while (!int.TryParse(numberNStr, out numberN))
        {
            Console.Write("Invalid input. Enter N again : ");
            numberNStr = Console.ReadLine();
        }
        // get number K
        Console.Write("Enter number K : ");
        string numberKStr = Console.ReadLine();
        int numberK;
        while (!int.TryParse(numberKStr, out numberK))
        {
            Console.Write("Invalid input. Enter K again : ");
            numberKStr = Console.ReadLine();
        }

        if (numberN < 0 || numberK < 0)
        {
            Console.WriteLine("Invalid input. The numbers should be positive. Start the program again.");
        }
        else
        {
            // save the result in a variable so we could use it more than once
            // and to escape the slow calculation of the Math.Pow
            int powerNK = (int)Math.Pow(numberN, numberK);

            for (int i = 0; i < powerNK; i++)
            {
                int conv = i;
                int[] num = new int[numberK];
                for (int j = 0; j < numberK; j++)
                {
                    num[numberK - j - 1] = conv % numberN;
                    conv = conv / numberN;
                }

                Console.Write("{0}{1}", '{', num[0] + 1);
                for (int j = 1; j < numberK; j++)
                {
                    Console.Write(", {0}", num[j] + 1);
                }
                if (i == powerNK - 1)   // after the last element we don't need comma
                {
                    Console.Write("}");
                }
                else
                {
                    Console.Write("}, ");
                }
            }
        }
        Console.WriteLine();
    }
}
